import requests
import json
from logger import log_message, log_to_file

base_url = "https://ad.xiaohongshu.com/api/leona/rtb"

def change_bid_crawl(unit_dict_cookie=None, account_id=None, unitIds=None, eventBid=None, result_text=None):
    headers = {
        "accept": "application/json, text/plain, */*",
        "accept-language": "zh-CN,zh;q=0.9",
        "content-type": "application/json",
        "origin": "https://ad.xiaohongshu.com",
        "priority": "u=1, i",
        "referer": f"https://ad.xiaohongshu.com/aurora/ad/manage/unit?vSellerId={account_id}",
        "sec-ch-ua": "\"Google Chrome\";v=\"135\", \"Not-A.Brand\";v=\"8\", \"Chromium\";v=\"135\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36",
        "v-seller-id": account_id,
        # "x-b3-traceid": "600c082c35d49677"
    }

    unit_url = f"{base_url}/unit/batch/bid"
    data = {
        "unitIds": [unitIds],
        "eventBid": eventBid
    }
    data = json.dumps(data, separators=(',', ':'))
    response = requests.post(url=unit_url, headers=headers, cookies=unit_dict_cookie, data=data)

    res_json_status = response.json()['msg']
    if response.json()['code'] == 0:
        log_message(result_text, f'单元ID - {unitIds} - 改价成功', 'green')
    else:
        log_message(result_text, f'单元ID - {unitIds} - 改价失败 - {res_json_status}', 'red')

    print(response.text)
    print(response)
